<template>
  <div>
    <div class="zuoce">
      <div class="zuo-top">计费管理 / 缴费类型管理</div>
      <el-form
        ref="form"
        :model="form"
        label-width="80px"
        inline
        class="zuo-mid"
      >
        <el-form-item label="">
          <el-input v-model="form.name" placeholder="项目价格"></el-input>
        </el-form-item>
        <el-form-item label="">
          <el-select v-model="form.region" placeholder="通知状态">
            <el-option label="已通知" :value="1"></el-option>
            <el-option label="未通知" :value="2"></el-option>
          </el-select>
        </el-form-item>
      </el-form>

      <el-tree
        :data="treeData"
        :props="treeProps"
        @node-click="handleTreeClick"
        accordion
        class="tree-wrapper"
        node-key="id"
        default-expanded-keys="[1, 11]"
      ></el-tree>
    </div>

    <div class="youce">
      <div class="you-top">
        <span class="youmulu">{{ title }}</span>
        <div class="anniumen">
          <el-row>
            <el-button
              type="primary"
              icon="el-icon-search"
              class="anniu"
              @click="cha()"
              >查询</el-button
            >
            <el-button
              type="success"
              icon="el-icon-plus"
              class="anniu"
              @click="xinzeng()"
              >新增</el-button
            >
            <el-button
              type="primary"
              icon="el-icon-refresh"
              class="anniu"
              @click="shuaxin()"
              >刷新</el-button
            >
            <el-button
              type="primary"
              icon="el-icon-upload2"
              class="anniu"
              @click="exportExcel"
              >导出</el-button
            >
          </el-row>
        </div>
      </div>

      <el-table :data="liebiao" border style="width: 100%" class="biaoge">
        <el-table-column
          prop="payname"
          label="缴费项目名称"
          width="120"
        ></el-table-column>
        <el-table-column
          prop="paylevel"
          label="缴费项目优先级"
          width="120"
        ></el-table-column>
        <el-table-column
          prop="paynum"
          label="项目用量/时长"
          width="120"
        ></el-table-column>
        <el-table-column
          prop="paymoney"
          sortable
          label="项目价格"
          width="120"
        ></el-table-column>
        <el-table-column label="创建时间" width="100">
          <template slot-scope="scope">
            {{ formatDate(scope.row.paytime) }}
          </template>
        </el-table-column>

        <el-table-column prop="username" label="通知人" width="120">
          <template slot-scope="scope">
            <span>{{ scope.row.username ? scope.row.username : "暂无" }}</span>
          </template>
        </el-table-column>

        <el-table-column prop="paystatus" label="状态" width="120">
          <template slot-scope="scope">
            <span v-if="scope.row.paystatus === 1">已通知</span>
            <span v-else-if="scope.row.paystatus === 2">未通知</span>
            <span v-else></span>
          </template>
        </el-table-column>

        <el-table-column label="操作">
          <template slot-scope="scope">
            <el-button size="mini" @click="handleEdit(scope.row)"
              >通知</el-button
            >
            <el-button type="primary" plain @click="chakan(scope.row)"
              >查看</el-button
            >
            <el-button
              size="mini"
              type="danger"
              @click="handleDelete(scope.row)"
              >作废</el-button
            >
          </template>
        </el-table-column>
      </el-table>

      <div class="block" style="float: right">
        <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="currentPage4"
          :page-sizes="[9, 10, 20, 50]"
          :page-size="9"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
        >
        </el-pagination>
      </div>

      <!-- 作废确认弹窗 -->
      <el-dialog title="提示" :visible.sync="dialogVisible" width="30%">
        <i class="el-icon-warning" style="color: orange"></i
        ><span>确定永久作废这条计费项目？</span>
        <span slot="footer" class="dialog-footer">
          <el-button @click="dialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="geiwosahn()">确 定</el-button>
        </span>
      </el-dialog>


      <el-dialog title="付费通知" :visible.sync="dialogVisible2" width="40%">
        <el-form ref="notifyForm" :model="notifyForm" label-width="20px">
          <el-form-item label="">
            <el-input
              v-model="notifyForm.username"
              placeholder="请输入用户账号"
              style="width: 40%; margin-right: 20px"
            ></el-input>
            <el-button
              type="primary"
              icon="el-icon-search"
              @click="tongzhicha()"
            ></el-button>
            <el-button
              type="warning"
              style="background: #f7ba2a"
              @click="chongzhitz"
              ><i class="el-icon-refresh-right"></i>重置</el-button
            >
          </el-form-item>
        </el-form>

        <el-table
          :data="tongzhi"
          border
          style="width: 100%"
          @row-click="handleRowClick"
          :row-class-name="rowClassName"
        >
          <el-table-column prop="" label="序号" width="60">
            <template slot-scope="scope">
              {{ scope.$index + 1 }}
            </template>
          </el-table-column>
          <el-table-column prop="username" label="用户账号" width="140">
          </el-table-column>
          <el-table-column prop="homeaddress" label="家庭住址" width="160">
          </el-table-column>
          <el-table-column prop="type" label="类型" width="130">
            <template slot-scope="scope">
              <span v-if="Number(scope.row.type) === 1">管理员</span>
              <span v-else>普通用户</span>
            </template>
          </el-table-column>
          <el-table-column prop="coststatus" label="缴费状态" width="140">
            <template slot-scope="scope">
              <span v-if="Number(scope.row.coststatus) === 1">已缴费</span>
              <span v-else>未缴费</span>
            </template>
          </el-table-column>
        </el-table>

        <div class="block1">
          <el-pagination
            @size-change="handleSizeChange2"
            @current-change="handleCurrentChange2"
            :current-page="currentPage5"
            :page-sizes="[7, 10, 20, 30]"
            :page-size="7"
            layout="total, sizes, prev, pager, next, jumper"
            :total="tongzhitotal"
          >
          </el-pagination>
        </div>

        <span slot="footer" class="dialog-footer">
          <el-button @click="dialogVisible2 = false">取 消</el-button>
          <el-button type="primary" @click="gotz()">通知</el-button>
        </span>
      </el-dialog>
    </div>
  </div>
</template>

<script>
import * as XLSX from "xlsx";

export default {
  data() {
    return {
      // 树形结构数据
      treeData: [
        {
          id: 1,
          label: "缴费项目",
          children: [
            {
              id: 11,
              label: "电费项目",
              children: [
                { id: 111, label: "电费目录表", cid: 7 }, // cid对应后端数据标识
              ],
            },
            {
              id: 12,
              label: "水费项目",
              children: [
                { id: 121, label: "水费固定月目录表", cid: 8 },
                { id: 122, label: "水费按量计价目录表", cid: 9 },
              ],
            },
            {
              id: 13,
              label: "天然气项目",
              children: [{ id: 131, label: "天然气目录表", cid: 10 }],
            },
            {
              id: 14,
              label: "物业费项目",
              children: [{ id: 141, label: "物业费目录表", cid: 11 }],
            },
            {
              id: 15,
              label: "宽带费项目",
              children: [{ id: 151, label: "宽带费目录表", cid: 12 }],
            },
          ],
        },
      ],
      treeProps: {
        children: "children",
        label: "label",
      },

      // 表单与查询数据
      form: {
        name: "", // 项目价格查询
        region: "", // 通知状态查询
      },
      notifyForm: {
        username: "", // 通知用户查询
      },

      // 表格数据
      liebiao: [], // 主表格数据
      total: 0, // 主表格总条数
      currentPage4: 1, // 主分页当前页
      currPage: 0, // 主分页请求页（后端从0开始）
      pageNum: 9, // 主分页每页条数

      // 通知弹窗数据
      dialogVisible2: false,
      tongzhi: [], // 通知用户列表
      tongzhiye: 0, // 通知分页请求页
      tongzhitiao: 7, // 通知分页每页条数
      tongzhitotal: 0, // 通知列表总条数
      currentPage5: 1, // 通知分页当前页
      selectedRow: null, // 选中的通知用户行
      selectedRowId: null, // 选中的项目ID
      selectedRowuId: null, // 选中的用户ID
      currentCostRow: null, // 当前操作的费用行数据

      // 作废弹窗数据
      dialogVisible: false,
      shanid: "", // 待作废的项目ID

      // 其他数据
      title: "电费目录表", // 右侧标题
      cid: 7, // 当前选中的缴费项目类型ID
    };
  },
  created() {
    // 初始化加载电费目录数据
    this.getlist();
  },
  methods: {
    // 树形节点点击事件（核心逻辑）
    handleTreeClick(data) {
      // 只有叶子节点（含cid）才触发数据加载
      if (data.cid) {
        this.cid = data.cid;
        this.title = data.label;
        this.currPage = 0;
        this.currentPage4 = 1;
        this.getlist(); // 加载对应类型的数据
      }
    },

    // 通知弹窗-重置查询
    chongzhitz() {
      this.notifyForm.username = "";
      this.tongzhiye = 0;
      this.currentPage5 = 1;
      this.loadUserList();
    },

    // 通知弹窗-查询用户
    tongzhicha() {
      this.tongzhiye = 0;
      this.currentPage5 = 1;
      this.loadUserList();
    },

    // 加载通知用户列表
    async loadUserList() {
      try {
        const res = await this.$axios.get(
          `http://community.byesame.com/users/getUserList?username=${this.notifyForm.username}&currPage=${this.tongzhiye}&pageNum=${this.tongzhitiao}`
        );
        this.tongzhi = res.data.data || [];
        this.tongzhitotal = res.data.total || 0;
      } catch (err) {
        this.$message.error("用户列表加载失败");
        console.error(err);
      }
    },

 
    async gotz() {
      if (!this.selectedRowuId || !this.currentCostRow) {
        this.$message.warning("请选择用户和费用项目");
        return;
      }
      try {
        await this.$axios.post(
          "http://community.byesame.com/cost/updateCostData",
          {
            u_id: this.selectedRowuId,
            c_id: this.currentCostRow.id,
            coststatus: this.selectedRow.coststatus,
            paystatus: 2,
            username: this.selectedRow.username,
            token:
              "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpZCI6MSwidXNlcm5hbWUiOiJhZG1pbiIsImVtYWlsIjoiMjQ1MzMxNzM1N0BxcS5jb20iLCJoZWFkIjoiMjAyNTEwMjcxNTE4NDA4MzUxMTQxLmpwZyIsInR5cGUiOiIxIiwiaWF0IjoxNzYxNjEyMTM5LCJleHAiOjE3NjE2OTg1Mzl9.GCKh0ZClDfwlY7U6q-QRKgGI2VSTVrPVqZFOEI7ewi0",
          }
        );
        this.dialogVisible2 = false;
        this.$message.success("通知成功");
        this.getlist();
      } catch (err) {
        this.$message.error("通知失败，请重试");
        console.error(err);
      }
    },

    // 通知用户表格-行选中样式
    rowClassName({ row }) {
      return row === this.selectedRow ? "current-row" : "";
    },

    // 通知用户表格-行点击事件
    handleRowClick(row) {
      this.selectedRow = row;
      this.selectedRowuId = row.id;
    },

    // 通知分页-每页条数变化
    handleSizeChange2(val) {
      this.tongzhitiao = val;
      this.tongzhiye = 0;
      this.currentPage5 = 1;
      this.loadUserList();
    },

    // 通知分页-当前页变化
    handleCurrentChange2(val) {
      this.currentPage5 = val;
      this.tongzhiye = val - 1;
      this.loadUserList();
    },

    // 作废弹窗-取消
    quxiao() {
      this.dialogVisible = false;
    },

    // 作废弹窗-确认删除
    async geiwosahn() {
      try {
        await this.$axios.get(
          `http://community.byesame.com/cost/delCostData?id=${this.shanid}&token=eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpZCI6MSwidXNlcm5hbWUiOiJhZG1pbiIsImVtYWlsIjoiMjQ1MzMxNzM1N0BxcS5jb20iLCJoZWFkIjoiMjAyNTEwMjcxNTE4NDA4MzUxMTQxLmpwZyIsInR5cGUiOiIxIiwiaWF0IjoxNzYxNjEyMTM5LCJleHAiOjE3NjE2OTg1Mzl9.GCKh0ZClDfwlY7U6q-QRKgGI2VSTVrPVqZFOEI7ewi0`
        );
        this.dialogVisible = false;
        this.$message.success("删除成功");
        this.getlist();
      } catch (err) {
        this.$message.error("删除失败，请重试");
        console.error(err);
      }
    },

    // 查看详情
    chakan(row) {
      localStorage.setItem("chakanid", row.id);
      this.$router.replace("/pay/ChaKan");
    },

    // 导出Excel
    exportExcel() {
      if (this.liebiao.length === 0) {
        this.$message.warning("暂无数据可导出");
        return;
      }
      const ws = XLSX.utils.json_to_sheet(this.liebiao);
      const wb = XLSX.utils.book_new();
      XLSX.utils.book_append_sheet(wb, ws, this.title);
      XLSX.writeFile(wb, `${this.title}_${new Date().getTime()}.xlsx`);
    },

    // 新增项目
    xinzeng() {
      this.$router.replace("/pay/XinZeng");
    },

    // 刷新表格
    shuaxin() {
      this.form.name = "";
      this.form.region = "";
      this.currPage = 0;
      this.currentPage4 = 1;
      this.getlist();
    },

    // 查询表格
    cha() {
      this.currPage = 0;
      this.currentPage4 = 1;
      this.getlist();
    },

    // 主分页-每页条数变化
    handleSizeChange(val) {
      this.pageNum = val;
      this.currPage = 0;
      this.currentPage4 = 1;
      this.getlist();
    },

    // 主分页-当前页变化
    handleCurrentChange(val) {
      this.currentPage4 = val;
      this.currPage = val - 1;
      this.getlist();
    },

    // 格式化日期
    formatDate(time) {
      if (!time) return "";
      const date = new Date(time);
      return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(
        2,
        "0"
      )}-${String(date.getDate()).padStart(2, "0")}`;
    },

    // 打开通知弹窗
    handleEdit(row) {
      this.currentCostRow = row; // 记录当前操作的费用行
      this.dialogVisible2 = true;
      this.notifyForm.username = "";
      this.tongzhiye = 0;
      this.currentPage5 = 1;
      this.loadUserList();
    },

    // 打开作废弹窗
    handleDelete(row) {
      this.shanid = row.id;
      this.dialogVisible = true;
    },

    // 加载主表格数据
    async getlist() {
      try {
        const res = await this.$axios.get(
          `http://community.byesame.com/cost/getCostData?c_id=${this.cid}&paymoney=${this.form.name}&paystatus=${this.form.region}&currPage=${this.currPage}&pageNum=${this.pageNum}`
        );
        this.liebiao = res.data.data || [];
        this.total = res.data.total || 0;
      } catch (err) {
        this.$message.error("数据加载失败");
        console.error(err);
      }
    },
  },
};
</script>

<style>
/* 基础样式 */
.el-table__row.current-row {
  background-color: #e6f7ff;
}
.status-active {
  color: #42b983;
}
.status-inactive {
  color: #f56c6c;
}

/* 表格与分页 */
.biaoge {
  width: 100%;
  height: 500px;
  overflow-y: auto;
  margin-bottom: 20px;
}
.block {
  margin: 1.875rem 0;
}
.block1 {
  margin: 10px 0;
  text-align: right;
}

/* 按钮样式 */
.anniumen {
  float: right;
}
.anniu {
  margin-top: 10px;
  margin-left: 20px;
  border: none;
}
.anniu:first-child {
  margin-left: 0;
}

/* 布局样式 */
.zuoce {
  display: inline-block;
  width: 30%;
  height: 700px;
  margin-right: 30px;
  vertical-align: top;
  border-right: 1px solid #f0f0f0;
  padding-right: 10px;
}
.youce {
  display: inline-block;
  width: 65%;
  height: 700px;
  vertical-align: top;
  padding: 0 10px;
}
.zuo-top {
  margin: 20px;
  font-size: 16px;
  font-weight: bold;
  color: #333;
}
.zuo-mid {
  margin: 0 20px 20px;
  padding: 10px 0;
}
.you-top {
  margin: 20px 0;
  padding-bottom: 10px;
}
.youmulu {
  font-size: 24px;
  font-weight: bold;
  color: #333;
}

/* 树形结构样式 */
.tree-wrapper {
  margin: 0 20px;
  padding: 10px 0;
}
.el-tree-node__content {
  height: 36px;
}
.el-tree-node__label {
  font-size: 14px;
}
.el-tree--accordion .el-tree-node.is-opened .el-tree-node__children {
  padding-left: 15px;
}
</style>